app.controller('ResourceModalCtrl', function ($scope, $modalInstance, toaster, param, ajax) {
    $scope.submitting = false;
    $scope.param = param;
    if ($scope.param.data == null) {
        $scope.param.data = {
            tickets: 0,
            routeId: 0,
            groupId: $scope.param.group.id,
            rate: 100,
        };
    }
    $scope.param.datalist = [];
    $scope.selected = { activate: false };
    $scope.routes = [$scope.param.group.route1, $scope.param.group.route2];
    $scope.tickets = [6, 4];
    $scope.vehicles = [];

    ajax.get('vehicle/rt/unattached', function (data) {
        if (data && data.code == 200) $scope.vehicles = data.result;
    });

    $scope.ok = function () {
        $scope.submitting = true;
        if ($scope.myForm.$valid) {
            if ($scope.param.type == 'insert') {
                if ($scope.selected.vehicles.length == 0) {
                    toaster.pop('warning', '提示', '请选择车辆。');
                    $scope.submitting = false;
                    return;
                }
                if (!$scope.selected.ticket) {
                    toaster.pop('warning', '提示', '请选择实际票数。');
                    $scope.submitting = false;
                    return;
                }
                if (!$scope.selected.route) {
                    toaster.pop('warning', '提示', '请选择当前线路。');
                    $scope.submitting = false;
                    return;
                }
                $scope.param.data.tickets = $scope.selected.ticket;
                $scope.param.data.status = $scope.selected.activate ? 2 : 1;
                $scope.param.data.routeId = $scope.selected.route.id;
                for (var idx in $scope.selected.vehicles) {
                    $scope.param.datalist.push($scope.selected.vehicles[idx].id);
                }
                $modalInstance.close($scope.param);
                $scope.submitting = false;
            } else if ($scope.param.type == 'update') {
                $modalInstance.dismiss('cancel');
                $scope.submitting = false;
            }
        }
    };

    $scope.cancel = function () {
        $modalInstance.dismiss('cancel');
        $scope.submitting = false;
    };
});